/**
 * 内部账号体系登录
 */
import { API } from '@/services/common/api'
import { token$$, loginFailed } from './info'

interface RespLoginInfo {
  token: string
  user: {
    id: number
    username: string
    createdAt: string
    isAdmin: boolean
  }
}

export async function register(name: string, password: string, login=true) {
  const res = await API<RespLoginInfo>('/user/register', {
    method: 'POST',
    data: { username: name, password },
  })
  if (login) {
    if (res.success) {
      token$$.next({ value: res.data.token, mayInvalid: false })
    } else {
      loginFailed(res.error || '注册失败')
    }
  }
  return res
}

export async function login(name: string, password: string) {
  const res = await API<RespLoginInfo>('/user/login', {
    method: 'POST',
    data: { username: name, password },
  })
  if (res.success) {
    token$$.next({ value: res.data.token, mayInvalid: false })
  } else {
    loginFailed(res.error || '登录失败')
  }
}

export function logout() {
  token$$.next(null)
  setTimeout(() => window.location.reload(), 500) // 以防万一，刷新一下网页。同时为了让潜在的通知消息显示出来，延迟一下再刷新
}
